import { Component, HostListener, OnInit } from '@angular/core';
import { IonicPage, MenuController, ModalController, NavController, ToastController, NavParams, App, AlertController } from 'ionic-angular';

import { Item } from '../../models/item';
import { Items } from '../../providers/providers';
import { Api } from "../../providers/api/api";
import { IndexComponent } from '../../components/index/index';
// import { OverViewPage } from '../over-view/over-view';
import { OverPathPage } from '../over-path/over-path';
import { RecyclingPage } from '../recycling/recycling';


import { SequenceEqualSubscriber } from "rxjs/operators/sequenceEqual";
import { QueOutput } from '../../models/quesinfo';
import { localbase } from '../../models/localbase';
// import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { AsyncPipe } from '@angular/common';
@IonicPage()
@Component({
  selector: 'page-list-master',
  templateUrl: 'list-master.html'
})
export class ListMasterPage implements OnInit {
  currentItems: Item[];
  questionStatus = 'on';
  resData;
  _s;
  isfirsttime = true;
  constructor(public navCtrl: NavController,
    public items: Items,
    public modalCtrl: ModalController,
    public toastCtrl: ToastController,
    public alertCtrl: AlertController,
    private api: Api,
    private app: App,
    private navparams: NavParams,
    // private transfer: FileTransfer,
    private file: File,
    public localbasefun: localbase,
    menu: MenuController) {
    menu.enable(false);
    this.currentItems = this.items.query();
    // this.navCtrl.setRoot(ListMasterPage);
  }
  states;
  ss;
  icon = [];
  show = [];
  onQuestionnaire = [];
  _DataId;
  _i;
  copies;
  /**
   * 未下载问卷列表
   */
  list: Array<any>;
  IconData = [];
  X;
  dd;
  _OverList;
  OverListArray;
  _sessList;
  ngOnInit() {
    // let cc = { id: 1 };
    // this.dd=1;
    // this.api.Testwl(cc).subscribe(async res => {
    //  this.dd=1;
    // },async error=>{
    //   this.dd=0;
    // });
  }

  showControl(i) {
    this.show[i] = !this.show[i]
  }


  /**
   * The view loaded, let's query our items for the list
   */
  async ionViewDidEnter() {
    // 获取进行中的问卷列表
    this.onQuestionnaire = await this.localbasefun.getQuesList();
    console.log(this.onQuestionnaire);
    if (this.onQuestionnaire) {
      this.onQuestionnaire.forEach(async oneq => {
        let fqid = oneq.FQId;
        let ptime = oneq.FPublishTime;
        let param = { FQId: fqid, publishtime: ptime }
        this.api.IsGengAsQue(param).subscribe(res => {
          oneq.gengx = res;
        });
        oneq["fenshu"] = await this.localbasefun.getQueNum(oneq.FQId);
      });
    }
    // 获取位下载的列表
    let userid = sessionStorage.getItem("userid");
    let param = { userid: userid }
    this.api.notDownloadList(param).subscribe(async res => {
      const reslut = <any>res;
      if (reslut && reslut.array) {
        let notDownArray = new Array<any>();
        let serverQues = <Array<any>>reslut.array;
        const downQues = await this.localbasefun.getQuesList();
        if (downQues) {
          downQues.forEach(downQ => {
            serverQues = serverQues.filter(serq => serq.FQId !== downQ.FQId);
          });
        }
        await this.localbasefun.addServerQues(serverQues);
      }
      this.list = await this.localbasefun.getServerQuesList();
      this.list.forEach(addAtr => {
        addAtr['icon'] = 'download';
      });
      // this.list = res;
    });
    this.OverList();

    // for(var i=0;i<this.list.array.length;i++){
    //   sessionStorage.removeItem("IconData"+i)
    // }
  }

  /**
   * Prompt the user to add a new item. This shows our ItemCreatePage in a
   * modal and then adds the new item to our data source if the user created one.
   */
  addItem() {
    let addModal = this.modalCtrl.create('ItemCreatePage');
    addModal.onDidDismiss(item => {
      if (item) {
        this.items.add(item);
      }
    })
    addModal.present();
  }

  /**
   * Delete an item from the list of items.
   */
  deleteItem(item) {
    this.items.delete(item);
  }

  /**
   * Navigate to the detail page for this item.
   */
  openItem(item: Item) {
    this.navCtrl.push('ItemDetailPage', {
      item: item
    });
  }

  // notDownloadList() {
  //   let userid = sessionStorage.getItem("userid");
  //   let param = { userid: userid }
  //   this.api.notDownloadList(param).subscribe(async res => {
  //     this.list = res;
  //     if (this.list.array !== "") {
  //       sessionStorage.setItem("sessList", JSON.stringify(this.list));
  //       for (var i = 0; i < this.list.array.length; i++) {
  //         sessionStorage.removeItem("IconData" + i);
  //         this.icon[i] = 'download';
  //         let localbasefun = this.localbasefun;
  //         this.list.array[i]["isdowned"] = await localbasefun.isDown(this.list.array[i].FQId);
  //         //  if(this.list.array[i]["isdowned"]==true)
  //         //  {
  //         //   this.list.array.splice(i,1);
  //         //  }
  //       }
  //       for (var s = 0; s < this.list.array.length; s++) {
  //         this.show[s] = false;
  //       }
  //     } else {
  //       let toast = this.toastCtrl.create({
  //         message: "没有数据",
  //         duration: 3000,
  //         position: 'top'
  //       });
  //       toast.present();
  //       return false;
  //     }
  //   })
  // }

  async questionnaireAnswers(p, s, i) {

    if (this.icon[i] == "pause") {
      let toast = this.toastCtrl.create({
        message: "已经下载,请到进行中查看！",
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
      return false;
    }
    this._s = s;
    // let param = { FQID: p };
    // //取问卷结构
    // await this.api.questionnaireAnswers(param).subscribe(res => {
    //    this.resData = res;
    //   this.navCtrl.push(IndexComponent, { resData: <QueOutput>this.resData, s: this._s, _i: i });
    // });
    let cc = { id: 1 };
    let dd = 0;
    // if(this.dd==0){
    //   let localbasefun = this.localbasefun;
    //   this.resData = await localbasefun.getQueByFqid(p);
    //   this.navCtrl.push(IndexComponent, { resData: <QueOutput>this.resData, s: this._s, _i: i, _dd: 0 });
    // }else{
    //   let localbasefun = this.localbasefun;
    //   this.resData = await localbasefun.getQueByFqid(p);
    //   this.navCtrl.push(IndexComponent, { resData: <QueOutput>this.resData, s: this._s, _i: i, _dd: 1 });
    // }
    this.api.Testwl(cc).subscribe(async res => {
      let localbasefun = this.localbasefun;
      this.resData = await localbasefun.getQueByFqid(p);
      this.navCtrl.push(IndexComponent, { resData: <QueOutput>this.resData, s: this._s, _i: i, _dd: 1 });
     },async error=>{
      let localbasefun = this.localbasefun;
      this.resData = await localbasefun.getQueByFqid(p);
      this.navCtrl.push(IndexComponent, { resData: <QueOutput>this.resData, s: this._s, _i: i, _dd: 0 });
     });


  }

  tabDowmloadIcon(ques) {
    if (ques.icon == "pause") {
      let toast = this.toastCtrl.create({
        message: "不可重复下载",
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
      return false;
    }
    // sessionStorage.setItem("IconData" + i, i);
    ques.icon = "pause";
    let param = { FQID: ques.FQId };
    this.api.questionnaireValidation(param).subscribe(res => {
      this.states = res;
      if (this.states.state == "1") {
        let thisque;
        this.api.questionnaireAnswers(param).subscribe(async res => {
          thisque = res;
          console.log(thisque);
          let localbasefun = this.localbasefun;
          await localbasefun.addQueDownLoad(ques.FQId, thisque);
          this.ionViewDidEnter();
          let toast = this.toastCtrl.create({
            message: "下载成功！",
            duration: 3000,
            position: 'bottom'
          });
          toast.present();
          return false;
        });
      } else if (this.states.state == "-1") {
        ques.icon = "download";
        let toast = this.toastCtrl.create({
          message: "问卷不存在",
          duration: 3000,
          position: 'bottom'
        });
        toast.present();
        return false;
      } else if (this.states.state == "-2") {
        let toast = this.toastCtrl.create({
          message: "问卷答题已结束",
          duration: 3000,
          position: 'bottom'
        });
        ques.icon = "download";
        toast.present();
        return false;
      } else if (this.states.state == "-3") {
        let toast = this.toastCtrl.create({
          message: "问卷未开始发放",
          duration: 3000,
          position: 'bottom'
        });
        ques.icon = "download";
        toast.present();
        return false;
      }
    })
  }

  //更新代码
  gengxinfun(thisquepar) {
    let localbasefun = this.localbasefun;
    let thisque;
    this.api.questionnaireAnswers({ fqid: thisquepar.FQId }).subscribe(async res => {
      thisque = res;
      //更新最新问卷
      await localbasefun.editQue(thisque.Que.FQId + "," + thisque.Que.FPublishTime, thisque);
      let toast = this.toastCtrl.create({
        message: "下载成功！",
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
      this.ionViewDidEnter();
    });
  }
  // data;

  // DataSplice(t, i, x) {
  //   if (this.onQuestionnaire && this.onQuestionnaire.length > 0) {
  //     for (var a = 0; a < this.onQuestionnaire.length; a++) {
  //       if (this.onQuestionnaire[a].FQId == this.list.array[i].FQId) {
  //         this.onQuestionnaire.splice(a, 1);
  //       }
  //     }
  //   }
  // }

  OnDelete(i, thisque) {
    let confirm = this.alertCtrl.create({
      title: '确认删除',
      buttons: [
        {
          text: '取消',
          handler: () => {

          }
        },
        {
          text: '删除',
          handler: async () => {
            this.onQuestionnaire.splice(i, 1);
            localStorage.setItem("localQuestion", JSON.stringify(this.onQuestionnaire))
            let localbasefun = this.localbasefun;
            await localbasefun.delQue(thisque.FQId);
            // this.notDownloadList();
          }
        }
      ]

    });
    confirm.present();
  }
  OnDeleteOver(i, thisque) {
    let confirm = this.alertCtrl.create({
      title: '确认删除',
      buttons: [
        {
          text: '取消',
          handler: () => {

          }
        },
        {
          text: '删除',
          handler: () => {
            this.OverListArray.splice(i, 1);
            this.localbasefun.saveOverQue(thisque.FQId);
            // localStorage.setItem("localQuestion",JSON.stringify(this.onQuestionnaire))
            // let localbasefun=new localbase();
            // localbasefun.delQue(thisque.FQId);
            this.OverList();
            // this.list=JSON.parse(sessionStorage.getItem("sessList"));
          }
        }
      ]

    });
    confirm.present();
  }

  OverList() {
    let userid = sessionStorage.getItem("userid");
    let param = { userid: userid };
    if (userid) {
      this.api.OverList(param).subscribe(res => {
        this._OverList = res;
        //
        this.OverListArray = this._OverList.array;
        //
        this.OverListArray.forEach(async oneq => {
          await this.localbasefun.delQue(oneq.FQId)
          let jzfs = "";
          let jzsj = "";
          let FEndNumOrTimearr = oneq.FEndNumOrTime.split(',');
          jzfs = FEndNumOrTimearr[0];
          jzsj = FEndNumOrTimearr[1];
          if ((jzsj == null) || (jzsj == "") || (jzsj == undefined)) {
            oneq["jztype"] = "fs";
            oneq["jz"] = jzfs + "份";
          }
          else {
            oneq["jztype"] = "sj";
            oneq["jz"] = jzsj.substr(0, jzsj.length - 6);
          }

        });
        //显示隐藏
        this.OverListArray.forEach(async oneq => {
          oneq["isdel"] = await this.localbasefun.isDelQue(oneq.FQId);

        });
        //获取份数
        this.OverListArray.forEach(async oneq => {
          const fenshuthis = await this.localbasefun.getQueNum(oneq.FQId);
          oneq["fenshu"] = fenshuthis;
        });
      })
    }
  }
  OverView() {//已结束查看
    this.navCtrl.push("OverViewPage");
  }
  OverPath(fqid, fs) {//已结束轨迹
    this.navCtrl.push("OverPathPage", { fqid: fqid, fs: fs });
  }
  recycli(FQId) {//回收
    this.navCtrl.push("RecyclingPage", { fqid: FQId });
    sessionStorage.setItem('recycfqid', FQId);
  }
  proceedpath(fqid, fs, ft) {//进行轨迹
    this.navCtrl.push("OverPathPage", { fqid: fqid, fs: fs, ft: ft });
  }

  // async notdownstart(i, list, onQuestionnaire) {//未下载states==1,下载
  //   const localbasenotdownstart = this.localbasefun;
  //   await localbasenotdownstart.notdownstarta(i, list, onQuestionnaire);
  // }
  doRefresh(refresher) {
    this.ionViewDidEnter();
    this.OverList();
    // console.log('Begin async operation', refresher);
    // location.reload();
    this.isfirsttime = false;
    setTimeout(() => {
      // console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
  }
}
